package com.ygqh.baby.controller.admin;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.po.AdminSku;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.po.YgMaterial;
import com.ygqh.baby.po.YgSkuMaterial;
import com.ygqh.baby.po.YgStock;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.YgMaterialService;
import com.ygqh.baby.service.YgSkuMaterialService;
import com.ygqh.baby.utils.JsonUtils;

@Controller
@RequestMapping("/admin/skumaterial")
public class SkuMaterialController  extends BaseController<Object, java.lang.Long>{
	
    @Autowired
	private YgMaterialService ygMaterialService;	
    @Autowired
	private YgSkuMaterialService ygSkuMaterialService;	
    @Autowired
	private FileService fileService;	
    
	@RequestMapping("searchMaterial")
	@ResponseBody
	public Map<String,Object> searchMaterial(String q,QueryInfo queryInfo) {
		
		ResultSet<YgMaterial> resultSet=ygMaterialService.search(queryInfo,q);
		
		return resultSet.toDatatables(null);
	}
	@RequestMapping("searchMaterialList")
	@ResponseBody
	public List<YgMaterial> searchMaterialList() {
		return ygMaterialService.find();
		
		
	}
	@RequestMapping("saveMaterial")
	@ResponseBody
	public Message saveMaterial(String material) {
		YgMaterial ygMaterial= JsonUtils.toObject(material, YgMaterial.class);
		ygMaterial.setCreateBy(getSession().getTrueName());
		ygMaterial.setCreateTime(new Date());
		//判断是否含有相同的名字
		if(checkName(ygMaterial.getMaterialName(),ygMaterial.getId())>0)
			return Message.error("辅料名称已经存在");
	   return ygMaterialService.saveOrUpdate(ygMaterial)==1?SUCCESS_MESSAGE:ERROR_MESSAGE;
	
	}
	@RequestMapping("updateMaterialStatus")
	@ResponseBody
	public Message updateMaterialStatus(Long id) {
		YgMaterial ygMaterial=new YgMaterial();		
		ygMaterial.setId(id);	
		ygMaterial.setStatus(DataStatus.Delete);
	   return ygMaterialService.update(ygMaterial)==1?SUCCESS_MESSAGE:ERROR_MESSAGE;
	
	}
	private int checkName(String name,Long id){
		return ygMaterialService.findName(name, id);
	}
	
	@RequestMapping("getSkuCostListByProductId")
	@ResponseBody
	public List<YgSkuMaterial> getSkuCostListByProductId(String productCode) {
		return ygSkuMaterialService.findSkuCostByProductId(productCode);
		
		
	}
	
	@RequestMapping("savaSkuCost")
	@ResponseBody
	public Message savaSkuCost(String skus) {
		List<YgSkuMaterial> list=JSON.parseObject(skus, new TypeReference<List<YgSkuMaterial>>(){});
		return ygSkuMaterialService.saveOrUpdate(list,getSession().getTrueName());
		
	}
	
	@RequestMapping("searchSkuList")
	@ResponseBody
	public Map<String,Object> searchSkuList(String productCode,String skuCode,String productName,QueryInfo queryInfo,String barCode, HttpServletRequest request, HttpServletResponse response) {
		ResultSet<YgSkuMaterial> ygSkuMaterial = ygSkuMaterialService.search(queryInfo,productCode,skuCode,productName,barCode);
	   return ygSkuMaterial.toDatatables(null);
	}
	
	@RequestMapping("printSkuMaterial")
	public void printSkuMaterial(String barCode, HttpServletRequest request, HttpServletResponse response) throws IOException {
		YgSkuMaterial ygSkuMaterial = ygSkuMaterialService.findSkuByBarCode(barCode);		
		byte[] bytes = fileService.downloadFromOss("template/print_sku_material.xlsx"); 		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("resultSet", ygSkuMaterial);
		DocumentHandler.DownloadExcel(bytes, barCode+".xlsx", dataMap, request, response);
	}
	@RequestMapping("readTemplate")
	@ResponseBody
	public Message readTemplate(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) throws IOException{
		InputStream is = uploadFile.getInputStream();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		Map map = new HashMap();
		List<YgSkuMaterial> skuList = new ArrayList<>();
		
		try {
			// Read the Sheet
			for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}
				// Read the Row
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow == null) {
						continue;
					}
					if (xssfRow != null) {	
						System.err.println(rowNum);
						YgSkuMaterial model = new YgSkuMaterial();
						XSSFCell skuCode = xssfRow.getCell(0);						
						XSSFCell productName = xssfRow.getCell(1);
						XSSFCell compent = xssfRow.getCell(2);
						XSSFCell sizeDesc = xssfRow.getCell(3);
						XSSFCell tagPrice = xssfRow.getCell(4);
						XSSFCell grade = xssfRow.getCell(5);
						XSSFCell standard = xssfRow.getCell(6);
						XSSFCell securityLevel = xssfRow.getCell(7);
						XSSFCell abcClass = xssfRow.getCell(8);
						XSSFCell checkupLevel = xssfRow.getCell(9);	
						XSSFCell barcode = xssfRow.getCell(10);
						model.setSkuCode(getValue(skuCode));
						if(model.getSkuCode()==null)
							continue;
						model.setTagName(getValue(productName));
						//对成分含量进行拆分
						String[] compentArr=compent.toString().replace("；", ";").split(";");
						for(int i=0;i<compentArr.length;i++){
							switch(i){
							case 0:
								model.setComponent1(compentArr[0].replace("：", ":"));
								break;
							case 1:
								model.setComponent2(compentArr[1].replace("：", ":"));
								break;
							case 2:
								model.setComponent3(compentArr[2].replace("：", ":"));
								break;
							case 3:
								model.setComponent4(compentArr[3].replace("：", ":"));
								break;
							case 4:
								model.setComponent5(compentArr[4].replace("：", ":"));
								break;
							}
							
						}
						model.setSizeDesc(getValue(sizeDesc));
						model.setTagPrice(getValue(tagPrice));
						model.setGrade(getValue(grade));
						model.setStandard(getValue(standard));
						model.setSecurityLevel(getValue(securityLevel));
						model.setAbcClass(getValue(abcClass));
						model.setCheckupLevel(getValue(checkupLevel));
						model.setBarCode(getValue(barcode));
						
						
						skuList.add(model);

					}
				}
			}
			return Message.success(skuList);
		} catch (Exception e) {
			return Message.error(skuList);
		}
	}
	@SuppressWarnings("static-access")
	private String getValue(XSSFCell hssfCell) {
		if (hssfCell == null)
			return null;
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			DecimalFormat df = new DecimalFormat("0");
			String str = df.format(hssfCell.getNumericCellValue());
			// 返回数值类型的值
			return str;
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}
	
	@RequestMapping("saveBatchSku")
	@ResponseBody
	public Message saveBatchSku(String skus) {
		List<YgSkuMaterial> ygSkuMaterial=JSON.parseObject(skus, new TypeReference<List<YgSkuMaterial>>(){});
		ygSkuMaterialService.updateSkuMaterial(ygSkuMaterial,getSession().getTrueName());
	    return SUCCESS_MESSAGE;
	
	}
	@RequestMapping("getSkuMaterial")
	@ResponseBody
	public YgSkuMaterial getSkuMaterial(String barCode) {
		YgSkuMaterial ygSkuMaterial=ygSkuMaterialService.findSkuByBarCode(barCode);

	    return ygSkuMaterial;
	
	}
	
	@RequestMapping("getSkuCode")
	
	public void getSkuCode(String barCodes, HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String[] skus=barCodes.split("\\r\\n");
		
		Map<String, Integer> mp=new HashMap<String,Integer>();
		Map<String,Integer> selectSkus=new HashMap<String, Integer>();
		for(String s:skus){
			s=s.trim();
			
			
			if(s.length()>9){
				if(!selectSkus.containsKey(s)){
					selectSkus.put(s,1);
				}else{
					Integer amount=selectSkus.get(s);
					selectSkus.remove(s);
					selectSkus.put(s,amount+1);
				}
			}else{
				
				if(!mp.containsKey(s)){
					mp.put(s,1);
				}else{
					Integer amount= mp.get(s);
					mp.remove(s);
					mp.put(s,amount+1);
				}
			}
			
		}
		//查询数据库 
		if(selectSkus.size()>0){
			List<String> codes=new ArrayList<String>();			
			for(String s :selectSkus.keySet()){
				codes.add(s);
			}
			List<YgSkuMaterial> codesMap=ygSkuMaterialService.findSkuByBarCodes(codes);
			//循环Map，及SelectSkus 添加到 mp 中
			for(YgSkuMaterial m:codesMap){				
				mp.put(m.getSkuCode(),selectSkus.get(m.getBarCode()));
				selectSkus.remove(m.getBarCode());
				
			}
		}
		
		byte[] bytes = fileService.downloadFromOss("template/scan_sku.xlsx"); 		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<YgStock> list=new ArrayList<YgStock>();
		for (Map.Entry<String, Integer> entry : mp.entrySet()) {  
			YgStock stock=new YgStock();
			stock.setSkuCode(entry.getKey());
			stock.setAmount(Long.parseLong(entry.getValue()+""));
			list.add(stock);
		}
		if(selectSkus.size()>0){
			for(String s :selectSkus.keySet()){
				YgStock stock=new YgStock();
				stock.setSkuCode(s);
				stock.setAmount(Long.valueOf(selectSkus.get(s)));
				list.add(stock);				
			}
		}
		dataMap.put("resultSet", list);
		
		DocumentHandler.DownloadExcel(bytes, new Date().getDate()+".xlsx", dataMap, request, response);
	}


	
}
